import riceService from '@/services/rice-service';
import { SearchOutlined } from '@ant-design/icons';
import { Button, Card, Input, Select, Space, Table, Tag, message } from 'antd';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';

const { Option } = Select;

const RiceVarietiesList = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [filters, setFilters] = useState({
    name: '',
    seed_id: '',
    drought_resistant: false,
    glutinous: false,
    form_type: '不限定',
    rice_type: '不限定',
  });
  const navigate = useNavigate();

  const columns = [
    {
      title: '品种ID',
      dataIndex: 'seed_id',
      key: 'seed_id',
      width: 100,
    },
    {
      title: '品种名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: any) => <span className="text-primary">{text}</span>,
    },
    {
      title: '母本',
      dataIndex: 'mother_parent',
      key: 'mother_parent',
      ellipsis: true,
    },
    {
      title: '品种类型',
      dataIndex: 'variety_type',
      key: 'variety_type',
      render: (text: any) => {
        let color = 'geekblue';
        if (text.includes('籼型')) color = 'volcano';
        if (text.includes('粳型')) color = 'green';
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '选育单位',
      dataIndex: 'breeding_unit',
      key: 'breeding_unit',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: any) => (
        <Button
          type="link"
          onClick={() =>
            navigate(`/dataManager/RiceVarietyDetail/${record.id}`)
          }
          className="text-blue-500"
        >
          查看详情
        </Button>
      ),
    },
  ];

  const fetchData = async (params = {}) => {
    setLoading(true);
    try {
      const response = await riceService.varieties_list({
        ...filters,
        page: params.current || pagination.current,
        per_page: params.pageSize || pagination.pageSize,
      });

      setData(response.data.data.items);
      setPagination({
        ...pagination,
        total: response.data.data.total,
        current: params.current || pagination.current,
        pageSize: params.pageSize || pagination.pageSize,
      });
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [filters]);

  const handleTableChange = (pagination) => {
    setPagination(pagination);
    fetchData(pagination);
  };

  const handleSearch = () => {
    setPagination({ ...pagination, current: 1 });
    fetchData({ ...pagination, current: 1 });
  };

  const handleReset = () => {
    setFilters({
      name: '',
      seed_id: '',
      drought_resistant: false,
      glutinous: false,
      form_type: '不限定',
      rice_type: '不限定',
    });
  };

  return (
    <div className="p-4">
      <Card
        title="水稻品种列表"
        bordered={false}
        extra={
          <Button type="primary" onClick={handleSearch}>
            <SearchOutlined /> 搜索
          </Button>
        }
      >
        <div className="mb-4 grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4">
          <div>
            <label className="block mb-1">品种名称</label>
            <Input
              placeholder="输入品种名称"
              value={filters.name}
              onChange={(e) => setFilters({ ...filters, name: e.target.value })}
            />
          </div>
          <div>
            <label className="block mb-1">品种ID</label>
            <Input
              placeholder="输入品种ID"
              value={filters.seed_id}
              onChange={(e) =>
                setFilters({ ...filters, seed_id: e.target.value })
              }
            />
          </div>
          <div>
            <label className="block mb-1">品种形式</label>
            <Select
              className="w-full"
              value={filters.form_type}
              onChange={(value) => setFilters({ ...filters, form_type: value })}
            >
              <Option value="不限定">不限定</Option>
              <Option value="籼型">籼型</Option>
              <Option value="粳型">粳型</Option>
            </Select>
          </div>
          <div>
            <label className="block mb-1">水稻类型</label>
            <Select
              className="w-full"
              value={filters.rice_type}
              onChange={(value) => setFilters({ ...filters, rice_type: value })}
            >
              <Option value="不限定">不限定</Option>
              <Option value="常规稻">常规稻</Option>
              <Option value="杂交稻">杂交稻</Option>
              <Option value="三系杂交稻">三系杂交稻</Option>
              <Option value="两系杂交稻">两系杂交稻</Option>
              <Option value="不育系">不育系</Option>
            </Select>
          </div>
          <div>
            <label className="block mb-1">特性筛选</label>
            <Space>
              <Select
                className="w-32"
                value={filters.drought_resistant}
                onChange={(value) =>
                  setFilters({ ...filters, drought_resistant: value })
                }
              >
                <Option value={false}>不限耐旱</Option>
                <Option value={true}>耐旱品种</Option>
              </Select>
              <Select
                className="w-32"
                value={filters.glutinous}
                onChange={(value) =>
                  setFilters({ ...filters, glutinous: value })
                }
              >
                <Option value={false}>不限糯性</Option>
                <Option value={true}>糯性品种</Option>
              </Select>
            </Space>
          </div>
          <div className="flex items-end">
            <Button onClick={handleReset}>重置</Button>
          </div>
        </div>

        <Table
          columns={columns}
          rowKey="id"
          dataSource={data}
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          bordered
          scroll={{ x: 'max-content' }}
        />
      </Card>
    </div>
  );
};

export default RiceVarietiesList;
